package com.dongbo.recorder.screenrecord.dialog;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.util.TypedValue;
import android.widget.TextView;

import com.dongbo.recorder.screenrecord.ui.fragment.HomeFragment;
import com.dongbo.recorder.screenrecord.R;
import com.lxj.xpopup.core.CenterPopupView;

import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

/**
 * @author GuoZi
 * @date :2020/5/5 19:24
 * @description:
 */
public class CountTimePop extends CenterPopupView {
    HomeFragment homeFragment;
    private TextView countTime;
    int resultCode;
    Intent data;

    private Disposable mDisposable;

    public CountTimePop(@NonNull Context context,HomeFragment fragment,int resultCode,Intent data) {
        super(context);
        this.homeFragment = fragment;
        this.resultCode = resultCode;
        this.data = data;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.pop_counttime;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        countTime = (TextView) findViewById(R.id.count_time);
        // 倒计时 10s
        mDisposable = Flowable.intervalRange(0, 6, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        countTime.setText((5-aLong)+"");
                        // 设置动画从小到大
                        ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f);
                        animator.setDuration(1000); // 动画持续时间1000毫秒
                        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {
                                // 获取当前动画的比例值[0,1]
                                float scale = animation.getAnimatedFraction();

                                // 设置文字大小，这里使用sp作为单位
                                countTime.setTextSize(TypedValue.COMPLEX_UNIT_SP, 80 * scale);
                            }
                        });

                        animator.start();
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        dismiss();
                        homeFragment.startGoRecord(resultCode,data);
                    }
                })
                .subscribe();
    }
}
